package com.qunar.crawler.utils;

import java.util.Random;

/**
 * @author waynechen Jun 4, 2012 8:30:31 PM
 */
public class ProbabilityUtils {
	public static final Random RAN = new Random();

	/**
	 * 有 p 的概率返回true<br>
	 * p的取值范围为: p&lt;=1 and p&gt;=0
	 * 
	 * @author waynechen
	 * @param p
	 * @return
	 */
	public static boolean probability(final double p) {
		if (p > 1 || p < 0)
			throw new RuntimeException("概率p有误, p的取值范围为: p<=1 and p>=0");
		int count = 0;
		double $p = p;
		while (true) {
			$p *= 10;
			int tmp = (int) $p;
			$p -= tmp;
			count++;
			if ($p <= 0)
				break;
		}
		int base = 1000 * count;
		int nextInt = RAN.nextInt(base) + 1;
		if (nextInt <= p * base)
			return true;
		return false;
	}
}
